package com.hydra.base.utils;

import org.springframework.data.domain.Sort;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 通用工具类
 * @Author 陈煜敏
 * @Date 2022/9/22 17:29
 */
public class CommonUtil2 extends CommonUtil {

    /**
     * 构建排序
     * @param sort  排序字符串，类似: xxx asc, aaa desc
     * @return      分页请求对象
     */
    public static Sort buildSort(String sort){
        List<Sort.Order> orders = null;
        if(sort != null){
            String[] array = sort.split(",");
            orders = Arrays.stream(array).map(item -> {
                item = item.trim();
                String[] arr = item.split(" ");
                String field = null;
                Sort.Direction direction = Sort.Direction.ASC;
                if(arr.length == 1){
                    field = arr[0];
                }else if(arr.length > 1){
                    field = arr[0];
                    if(arr[1].trim().equals("desc")){
                        direction = Sort.Direction.DESC;
                    }
                }
                if(StringUtil.isEmpty(field)){
                    return null;
                }
                field = field.trim();
                return new Sort.Order(direction, field);
            }).filter(Objects::nonNull).collect(Collectors.toList());
        }
        if(orders == null || orders.isEmpty()){
            return null;
        }
        return Sort.by(orders);
    }

}
